package com.platform.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.base.PageUtil;
import com.platform.base.R;
import com.platform.base.Tree;
import com.platform.base.mvc.BaseController;
import com.platform.dto.Modular;
import com.platform.dto.Right;
import com.platform.exception.BizException;
import com.platform.logger.annotation.ApiLog;
import com.platform.service.IModular;
import com.platform.service.IRight;
import com.platform.utils.StringUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @ClassName:  RightController   
 * @desc:系统权限管理
 * @author: <a href="mailto:15909910367@163.com">吴先生</a>  
 * @date:   2021年12月17日 下午6:38:54   
 *     
 * @Copyright: 2021 吴元森.
 */
@Controller
@RequestMapping("/right")
@Api(tags = "OMS-权限管理模块")
public class RightController extends BaseController {

	@Autowired
	private IRight services;
	@Autowired
	private IModular modularService;

	@RequestMapping(value = "data", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "分页查询")
	public Object selectAll(Right dto, Integer start, Integer limit, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		PageUtil pageUt = new PageUtil();
		pageUt.setPageIndex(start);
		pageUt.setPageSize(limit);
		pageUt.setParams(BeanUtil.beanToMap(dto));
		List<Right> servicesList = services.selectByPaging(pageUt);
		return R.success(servicesList, pageUt.getTotal());
	}

	@ApiLog(value = "权限数据删除", desc = "系统权限数据删除")
	@SuppressWarnings("all")
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除数据")
	public Object delete(String ids, HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws IOException {
		boolean isSuccess = false;
		String[] removes = ids.split(",");
		for (int i = 0; i < removes.length; i++) {
			Right right = services.get(removes[i]);
			isSuccess = services.delete(right);
		}
		return R.success();
	}

	@ApiLog(value = "权限数据新增", desc = "系统权限数据新增")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "新增数据")
	public Object insert(@Valid Right dto, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		StringBuffer rightCodeSb = new StringBuffer();
		Modular m = getModularEn(dto.getSourcescode());
		String rightEn = m.getModularen();
		for (String str : dto.getRightcodes()) {
			rightCodeSb.append(rightEn + "_" + str);
			rightCodeSb.append(",");
		}
		dto.setRightcode(rightCodeSb.toString());
		dto.setCreateDate(new Date());
		dto.setCreater(getName());
		if (services.insert(dto)) {
			return R.success();
		} else {
			return R.fail();
		}
	}
	@ApiLog(value = "获取系统资源菜单模块名称", desc = "获取系统资源菜单模块名称")
	private Modular getModularEn(String sourcesCode) {
		Map<String, Object> searchMap = MapUtil.newHashMap();
		searchMap.put("modularcode", sourcesCode);
		List<Modular> modulars = modularService.selectAll(searchMap);
		return modulars.get(0);
	}

	@ApiLog(value = "权限数据修改", desc = "系统权限数据修改")
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "修改数据")
	public Object update(@Valid Right dto, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		if (!StringUtils.isEmpty(dto.getSourcescode())) {
			StringBuffer rightCodeSb = new StringBuffer();
			Modular m = getModularEn(dto.getSourcescode());
			String rightEn = m.getModularen();
			for (String str : dto.getRightcodes()) {
				rightCodeSb.append(rightEn + "_" + str);
				rightCodeSb.append(",");
			}
			dto.setRightcode(rightCodeSb.toString());
		}
		dto.setLastModifyDate(new Date());
		dto.setLastModifier(getName());
		if (services.update(dto)) {
			return R.success();
		} else {
			return R.fail();
		}
	}

	@RequestMapping(value = "find", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取单条数据")
	public Object get(String code, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		return services.get(code);
	}

	/**
	 * @Title: initMenuRight
	 * @desc: 初始化菜单权限，慎用 void
	 */
	@ApiLog(value = "初始化系统资源权限数据", desc = "初始化系统资源权限数据")
	@RequestMapping(value = "initMenuRight", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "初始化系统资源权限数据")
	public R<?> initMenuRight(String ids) {
		Map<String, Object> menuSearchMap = MapUtil.newHashMap();
//		menuSearchMap.put("extendclass", "menu");
//		menuSearchMap.put("parent_", "0001002004");// 这里是指定特定的资源权限生成
//		menuSearchMap.put("id", "109");
		menuSearchMap.put("id", ids);
		List<Modular> menuList = modularService.selectAll(menuSearchMap);
		for (Modular menu : menuList) {
			String[] rights = menu.getModularright().split(",");
			services.deleteBySourceCode(menu.getModularcode());
			for (String right : rights) {
				Right dto = new Right();
				dto.setRightname(menu.getName() + "-" + convertRightCodeToEn(right) + "权限");
				dto.setRightcode(menu.getModularen().toUpperCase() + "_" + right.toUpperCase());
				dto.setCreateDate(new Date());
				dto.setCreater(getName());
				dto.setSourcescode(menu.getModularcode());
				dto.setModularname(menu.getShowname());
				services.insert(dto);
			}
			menu.setInitMenu(1);
			modularService.update(menu);
		}
		return R.success();
	}

	private String convertRightCodeToEn(String rightCode) {
		String text = "";
		switch (rightCode) {
		case "SAVE":
			text = "新增";
			break;
		case "EDIT":
			text = "修改";
			break;
		case "DELETED":
			text = "删除";
			break;
		case "FILED":
			text = "归档";
			break;
		case "DOWNLOAD":
			text = "下载";
			break;
		case "PRINT":
			text = "打印";
			break;
		case "FIND":
			text = "查询";
			break;
		}
		return text;
	}

	@RequestMapping(value = "authorizationModular", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	@ApiOperation(value = "获取授权的菜单资源")
	public Object authorizationModular(String parentCode, String roleCode) {
		List<Tree> treeList = new ArrayList<Tree>();
		StringBuffer rightSources = new StringBuffer();
		List<String> rightSourcesList = this.services.findSourceByRole(roleCode);
		for (String str : rightSourcesList) {
			rightSources.append(str);
			rightSources.append(",");
		}
		Map<String, Object> searchMap = MapUtil.newHashMap();
		searchMap.put("parent", StringUtils.isEmpty(parentCode) ? "0" : parentCode);
		try {
			treeList = services.authorizationModular(searchMap);
			modularListBuildRight(treeList, rightSources.toString());
		} catch (BizException e) {
		}
		return treeList;
	}

	private void modularListBuildRight(List<Tree> modulars, String sources) throws BizException {
		List<Tree> modularList = new ArrayList<Tree>();
		for (Tree m : modulars) {
			Map<String, Object> childrenMap = MapUtil.newHashMap();
			childrenMap.put("parent", m.getSourcesCode());
			List<Tree> childrenList = this.services.authorizationModular(childrenMap);
			if ((childrenList != null) && (childrenList.size() > 0)) {
				modularListBuildRight(childrenList, sources);
			} else {
				m.setLeaf(true);
				if (m.getSourcesCode().equals("0001")) {
					modularList.add(m);
				}
				Map<String, Object> rightMap = MapUtil.newHashMap();
				rightMap.put("sourcesCode", m.getSourcesCode());
				List<Tree> rightTreeNone = this.services.queryRightByModular(rightMap);
				if (rightTreeNone.size() == 0) {
					continue;
				}
				List<Tree> rightTree = new ArrayList<Tree>();
				boolean isChooseChild = false;
				for (Tree tree : rightTreeNone) {
					tree.setChecked(sources.contains(tree.getSourcesCode()));
					if(tree.isChecked()) {isChooseChild=true;}
					tree.setLeaf(Boolean.TRUE.booleanValue());
					rightTree.add(tree);
				}
				m.setChecked(isChooseChild);
				m.setLeaf(false);
				m.setChildren(rightTree);

				continue;
			}
			m.setChildren(childrenList);
		}
		modulars.removeAll(modularList);
	}
}
